package upcweb.web;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import upcweb.modelo.ClsSolicitud;
import upcweb.modelo.ClsUsuario;
import upcweb.negocio.BsUsuario;
import upcweb.util.CheckLogin;

@Controller
public class SesionController {
	
	@RequestMapping(value = "/inicio" , method = RequestMethod.POST)
	protected ModelAndView homePage(HttpServletRequest request,
		HttpServletResponse response){	
		BsUsuario bsUs = new BsUsuario();
		CheckLogin chkLog = new CheckLogin();
		
		ClsUsuario usr = chkLog.getSession(request, response);
		if (usr==null){
		String user = request.getParameter("user");
		String pwd = request.getParameter("pwd");
		usr  = bsUs.checkLogin(new ClsUsuario(user, pwd));
		}
		ModelAndView mv = null;
/*		System.out.println(user);
		System.out.println(pwd);
		System.out.println("Verificar Login...");*/
		if (usr!=null){
		chkLog.setSesion(request, usr);
		mv = new ModelAndView("mvHome");
		mv.addObject("fromLogin","X");
		mv.addObject("login"," ");
		mv.addObject("usuario",usr);
		}
		else {			
		//	System.out.println("Not Loged..");
		mv = new ModelAndView("mvLogin");
		
//		mv.addObject("end","false");	
//		mv.addObject("login","X");
		}
		return mv;
	}
	
	@RequestMapping(value = "/login" , method = RequestMethod.POST)
	protected ModelAndView outSesion(HttpServletRequest request,
			HttpServletResponse response){			
		ModelAndView mv = new ModelAndView("mvLogin");		
		return mv;
	}
	
	
	@RequestMapping(value = "/endSesion" , method = RequestMethod.POST)
	protected ModelAndView finalizaSesion(HttpServletRequest request,
			HttpServletResponse response){
		try {
			HttpSession ses = (HttpSession)request.getSession();
			if (ses.getAttribute("sesion")!=null){
				ses.setAttribute("sesion", null);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		ModelAndView mv = new ModelAndView("mvLogin");
		mv.addObject("end","true");	
		return mv;
	}
	
}
